//
//  ARIndexWorkCell.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/8.
//

import UIKit
import SnapKit
import AttributedString

/// 首页的作品cell
class ARIndexWorkCell: UICollectionViewCell {

    var work: ARWorkModel? {
        didSet {
            guard let work = work else {
                return
            }
            self.configCell(work)
        }
    }
    
    // MARK: - Init
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // Setup UI
        self.setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    
    private func setupUI() {
        self.contentView.backgroundColor = .clear
        
        self.contentView.addSubview(containerView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(likeView)
        containerView.addSubview(contentLabel)
        containerView.addSubview(commentedUsersView)
        containerView.addSubview(checkLabel)
 
        containerView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(5)
            make.bottom.equalToSuperview().offset(-5)
            make.right.equalToSuperview()
            make.left.equalToSuperview().offset(40)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(20)
        }
        
        likeView.snp.makeConstraints { make in
            make.height.equalTo(14)
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(18)
        }
        
        contentLabel.snp.makeConstraints { make in
            make.left.right.equalTo(titleLabel)
            make.top.equalTo(likeView.snp.bottom).offset(16)
            make.bottom.equalTo(commentedUsersView.snp.top).offset(-16)
        }
        
        commentedUsersView.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.height.equalTo(24)
            make.bottom.equalTo(checkLabel.snp.top).offset(-16)
        }
        
        checkLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.width.equalTo(70)
            make.height.equalTo(24)
            make.bottom.equalToSuperview().offset(-24)
        }
    }
    
    private func configCell(_ work: ARWorkModel) {
        titleLabel.text = work.workTitle
        // 点赞
        likeView.updateLikeNum(work.likeNum ?? 0)
        // 内容
        let content = ASAttributedString.init(string: work.workDescription,
                                              .foreground(.black.withAlphaComponent(0.5)),
                                              .font(ARHelper.font(11, weight: .regular)),
                                              .paragraph(.alignment(.left), .maximumLineHeight(20), .minimumLineHeight(20), .lineBreakMode(.byTruncatingTail)))
        contentLabel.attributedText = content.value
        
        // 评论人数
        if let commentedUser = work.commentedAuthor, commentedUser.isEmpty == false {
            commentedUsersView.isHidden = false
            commentedUsersView.updateCommentedUsers(commentedUser)
        } else {
            commentedUsersView.isHidden = true
        }
    }
    
    // MARK: - Lazy

    private lazy var containerView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 18
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
        view.backgroundColor = .white
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.3
        view.layer.shadowOffset = .init(width: 1, height: 1)
        view.layer.shadowRadius = 3
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = ARHelper.font(18, weight: .medium)
        label.textColor = UIColor(hexString: "#202020")
        return label
    }()
    
    private lazy var likeView: ARIndexWorkLikeView = {
        let view = ARIndexWorkLikeView(frame: .zero)
        return view
    }()
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        return label
    }()
    
    private lazy var commentedUsersView: ARCommentedUserView = {
        let view = ARCommentedUserView()
        return view
    }()
    
    private lazy var checkLabel: UILabel = {
        let label = UILabel()
        label.text = ARHelper.localString("Check")
        label.font = ARHelper.font(14, weight: .regular)
        label.textColor = .init(hexString: "#4F9FE9")
        label.layer.cornerRadius = 12
        label.backgroundColor = .init(hexString: "#DBF2FF")
        label.layer.masksToBounds = true
        label.textAlignment = .center
        return label
    }()
}

/// 首页 - 点赞人数的view
fileprivate class ARIndexWorkLikeView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        self.addSubview(label)
        self.addSubview(starView)
        
        label.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview()
        }
        
        starView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(label.snp.right).offset(6)
            make.right.equalToSuperview()
        }
    }
    
    /// 更新点赞人数
    func updateLikeNum(_ num: Int) {
        
        if num <= 0 {
            label.text = ""
            return
        }
        
        label.text = String(num) + " " + ARHelper.localString("People praised it.")
    }
    
    // MARK: - Lazy
    
    private lazy var label: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#39BAE8")
        label.font = ARHelper.font(12, weight: .regular)
        return label
    }()
    
    private lazy var starView: UIImageView = {
        let view = UIImageView(image: .init(named: "index_star"))
        return view
    }()
    
}

/// 已评论的view
fileprivate class ARCommentedUserView: UIView {
    
    // MARK: - Private property
    
    /// 图片数组
    private var commentedUserAvatars: [UIImageView] = []
    
    // MARK: - Init
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        self.addSubview(numsLabel)
        self.addSubview(label)
        
        label.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(0)
        }
        
        numsLabel.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(0)
        }
    }
    
    // MARK: - Action
    
    func updateCommentedUsers(_ authors: [ARUserModel]) {
        
        if authors.isEmpty {
            return
        }
        
        commentedUserAvatars.removeAll { view in
            view.removeFromSuperview()
            return true
        }
        
        let maxCount = 2
        
        var i = 0
        var lastView: UIView?
        for author in authors {
            
            if i >= maxCount {
                break
            }

            let avatarView = UIImageView()
            avatarView.backgroundColor = .gray.withAlphaComponent(0.8)
            avatarView.layer.cornerRadius = 4
            avatarView.layer.masksToBounds = true
            avatarView.ar.setImage(author.trueAvatar)
            self.addSubview(avatarView)
            commentedUserAvatars.append(avatarView)
            
            avatarView.snp.makeConstraints { make in
                make.width.height.equalTo(24)
                make.centerY.equalToSuperview()
                if let lastView = lastView {
                    make.left.equalTo(lastView.snp.right).offset(12)
                } else {
                    make.left.equalToSuperview()
                }
            }
            
            lastView = avatarView
            i += 1
        }

        let labelPadding: CGFloat
        if authors.count > 2 {
            // 展示人数
            numsLabel.text = "+\(authors.count)"
            numsLabel.isHidden = false
            numsLabel.snp.updateConstraints { make in
                make.left.equalToSuperview().offset((24 + 12) * i)
            }
            
            labelPadding = (24.0 + 12.0) * CGFloat(i + 1) + 8.0
        } else {
            numsLabel.isHidden = true
            labelPadding = (24.0 + 12.0) * CGFloat(i) + 8.0
        }
        label.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(labelPadding)
        }
    }
    
    // MARK: - Lazy
    
    private lazy var label: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#39BAE8")
        label.font = ARHelper.font(12, weight: .regular)
        label.text = ARHelper.localString("People have commented.")
        return label
    }()
    
    private lazy var numsLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#36B7F4")
        label.backgroundColor = .init(hexString: "#DBF2FF")
        label.font = ARHelper.font(12, weight: .regular)
        label.layer.cornerRadius = 4
        label.isHidden = true
        return label
    }()
}
